import React, { useState, useRef } from "react";
import { Modal, Table, Button, Input } from "antd";
import * as XLSX from 'xlsx'
import {
  FileTextOutlined,
  FolderOpenOutlined,
  RestOutlined,
  FolderAddOutlined,
} from '@ant-design/icons';
import './index.scss'
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

const Index = (props) => {
  const [file, setFile] = useState()
  const [filearray, setFileArray] = useState({})
  const [filename, setFileName] = useState()
  const [filekey, setFileKey] = useState(0)
  const [filekeylength, setFileKeyLength] = useState(0)
  const [useIf, setUseIf] = useState(false)
  const [resid, setResId] = useState(0)
  const [searchcontent, setSeachContent] = useState('')
  //pdf预览功能
  const [numPages, setNumPages] = useState(null);
  const [fileresname, setFileResName] = useState('');
  const [filetype, setFileType] = useState('');
  const [filecontent, setFileContent] = useState('');
  const [searchIf, setSearchIf] = useState(true);
  const inputRef = useRef();
  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setFileKey(selectedRowKeys)
      setFileKeyLength(selectedRowKeys.length)
    },
    // onSelect: (record, selected, selectedRows) => {
    //   console.log(record, selected, selectedRows);
    // },
    // onSelectAll: (selected, selectedRows, changeRows) => {
    //   console.log(selected, selectedRows, changeRows);
    // },
  };
  const resName = (data) => {
    setUseIf(data)
    setIsModalOpen(true);
  }
  const [checkStrictly, setCheckStrictly] = useState(true);
  const columns = [
    {
      title: '文件名',
      dataIndex: 'filename',
      key: 'filename',
    },
    // {
    //   title: '更新时间',
    //   dataIndex: 'time',
    //   key: 'time',
    //   width: '20%',
    // },
  ];
  const columns2 = [
    {
      title: '图片',
      dataIndex: '图片',
      key: '分类',
      render: function (text, record, index) {
        return <img src={text} style={{ width: 80 }} />
      }
    },
    {
      title: '分类',
      dataIndex: '分类',
      key: '分类',
    },
    {
      title: '品牌',
      dataIndex: '品牌',
      key: '分类',
    },
    {
      title: '价格',
      dataIndex: '价格',
      key: '价格',
    },
    {
      title: '商品名',
      dataIndex: '商品名',
      key: '商品名',
    },
    {
      title: '商品描述',
      dataIndex: '商品描述',
      key: '商品描述',
    },
  ];
  const [data, setData] = useState([
    {
      key: 1,
      filename: (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <FolderOpenOutlined
            style={{ color: 'yellow', fontSize: 25 }} />
          <span id={1} onContextMenu={(e) => {
            e.preventDefault()
            setResId(Number(e.target.id))
            resName(true)
          }}>人教版五年级上册</span>
        </div>
      ),
      time: 0,
      name: "人教版五年级上册",
      children: [],
    },
    {
      key: 2,
      filename: (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <FolderOpenOutlined
            style={{ color: 'yellow', fontSize: 25 }} />
          <span id={2} onContextMenu={(e) => {
            e.preventDefault()
            setResId(Number(e.target.id))
            resName(true)
          }}>人教版五年级下册</span>
        </div>
      ),
      time: 60,
      name: "人教版五年级下册",
      children: [],
    },
  ])
  const [data2, setData2] = useState([])
  const [data3, setData3] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = (data) => {
    setUseIf(data)
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleOk2 = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setFile('')
    setIsModalOpen(false);
  };
  const deleTableData = () => {
    const newData = []
    data.forEach(item => {
      newData.push(item)
    })
    filekey.forEach(k => {
      function deleData(data2) {
        data2.forEach(item => {
          if (item.key <= 10) {
            deleData(item.children)
          }
          const num = data2.findIndex(item2 => {
            return item2.key === k
          })
          if (num >= 0) {
            data2.splice(num, 1)
          }
        })
      }
      deleData(newData)
    })
    setData(newData)
  }
  const deleTableData3 = () => {
    const newData = []
    data3.forEach(item => {
      newData.push(item)
    })
    filekey.forEach(k => {
      function deleData(data2) {
        data2.forEach(item => {
          if (item.key <= 10) {
            deleData(item.children)
          }
          const num = data2.findIndex(item2 => {
            return item2.key === k
          })
          if (num >= 0) {
            data2.splice(num, 1)
          }
        })
      }
      deleData(newData)
    })
    setData3(newData)
  }
  return (
    <div className="courseManage">
      <div className="courseManage_header">
        <span style={{ fontWeight: 900 }}>上传:</span>
        <Button type="primary" disabled={filekeylength === 1 ? false : true} onClick={() => {
          inputRef.current.click()
        }}>
          {filekeylength !== 0 ? '' : '选中一个文件夹'}
          {filekeylength !== 1 ? '' : '点击上传文件'}
          {filekeylength !== 2 ? '' : '只能选一个'}
        </Button>
        <Button type="primary" disabled={filekeylength !== 0 ? false : true} style={{ display: 'flex', alignItems: 'center', marginLeft: 20 }} onClick={() => {
          if (searchIf) {
            deleTableData()
          } else {
            deleTableData3()
            deleTableData()
            setSeachContent('')
            setSearchIf(true)
          }
        }}>
          <RestOutlined style={{ fontSize: 25 }} />删除
        </Button>
        <Button type="primary" style={{ display: 'flex', alignItems: 'center', marginLeft: 20 }} onClick={() => {
          const newData = []
          data.forEach(item => {
            newData.push(item)
          })
          newData.push({
            key: newData.length + 1,
            filename: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <FolderOpenOutlined
                  style={{ color: 'yellow', fontSize: 25 }} />
                <span id={newData.length + 1} onContextMenu={(e) => {
                  setResId(Number(e.target.id))
                  e.preventDefault()
                  resName(true)
                }}>新建文件夹</span>
              </div>
            ),
            time: 0,
            name: '新建文件夹',
            children: [],
          })
          setData(newData)
        }}>
          <FolderAddOutlined style={{ fontSize: 25 }} />新建文件夹
        </Button>
        <input className="inputBox" placeholder="请输入搜索内容" value={searchcontent} onChange={(e) => {
          e.target.value ? setSearchIf(false) : setSearchIf(true)
          setSeachContent(e.target.value)
          if (e.target.value) {
            const newData = []
            function setStr(data) {
              data.forEach(item => {
                if (item.name.includes(e.target.value)) {
                  newData.push(item)
                }
                if (item.children) {
                  setStr(item.children)
                }
              })
            }
            setStr(data)
            setData3(newData)
          } else {
            setData(data)
          }
        }} />
        <input name="fileToUpload" type="file" hidden ref={inputRef} value={filecontent} onChange={ (e) => {
          setFileName(e.target.files[0].name)
          setFileType(e.target.files[0].name.split('.')[1])
          const name=e.target.files[0].name
          if (e.target.files[0].name.split('.')[1] === 'pdf' || e.target.files[0].name.split('.')[1] === 'png' || e.target.files[0].name.split('.')[1] === 'jpeg') {
            const reader = new FileReader()
            reader.readAsDataURL(e.target.files[0])
            reader.onload = () => {
              setFileArray((obj) => {
                obj[name] = reader.result
                return obj
              })
            }
          } else if (e.target.files[0].name.split('.')[1] === 'xlsx') {
            const reader = new FileReader()
            reader.readAsBinaryString(e.target.files[0])
            reader.onload = () => {
              const box = XLSX.read(reader.result, { type: "binary" })
              const info = box.Sheets[box.SheetNames[0]]
              const res = XLSX.utils.sheet_to_json(info)
              setData2(res)
              setFile(res)
              setFileArray((obj) => {
                obj[name] = res
                return obj
              })
            }
          }
          setData((data) => {
            const newData = []
            data.forEach(item => {
              if (item.key === filekey[0]) {
                item.children.push({
                  key: filekey[0] * 10 + item.children.length + 1,
                  filename: (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <FileTextOutlined
                        style={{ fontSize: 25 }} />
                      <span id={e.target.files[0].name} onClick={(e) => {
                        showModal(false)
                        setFileType(e.target.id.split('.')[1])
                        setFile(filearray[e.target.id])
                        // setFileType(e.target.id.sp)
                      }}>{e.target.files[0].name}</span>
                    </div>
                  ),
                  time: 60,
                  name: e.target.files[0].name
                })
              }
              newData.push(item)
            })
            return newData
          })
          setFileContent('')
        }} />
      </div>
      <Modal title={useIf ? '' : "文件查看"} open={isModalOpen} onOk={() => {
        useIf ? handleOk2() : handleOk()
      }} onCancel={handleCancel} width={useIf ? 300 : 1000} footer={null} style={{ height: useIf ? 200 : 600 }}>
        {
          useIf ? (
            <div className="resnameBox">
              修改名字为:
              <Input placeholder="请输入" onChange={(e) => {
                setFileResName(e.target.value)
              }} />
              <div className="resnameBox_btn">
                <Button type="primary" onClick={() => {
                  setIsModalOpen(false)
                }}>取消</Button>
                <Button type="primary" onClick={() => {
                  const newData = []
                  data.forEach(item => {
                    newData.push(item)
                  })
                  const obj = newData.find(item => {
                    return item.key === resid
                  })
                  obj.filename = (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <FolderOpenOutlined
                        style={{ color: 'yellow', fontSize: 25 }} />
                      <span id={newData.length + 1} onContextMenu={(e) => {
                        setResId(Number(e.target.id))
                        e.preventDefault()
                        resName(true)
                      }}>{fileresname}</span>
                    </div>
                  )
                  obj.name = fileresname
                  setData(newData)
                  setIsModalOpen(false)
                }}>确认修改</Button>
              </div>

            </div>
          ) : (file ? (filetype === 'pdf' ? ((<Document file={file} onLoadSuccess={onDocumentLoadSuccess} width={700}>
            {Array.from(new Array(numPages), (el, index) => (
              <Page
                key={`page_${index + 1}`}
                pageNumber={index + 1}
                renderAnnotationLayer={false}
                renderTextLayer={false}
                width={930}
              />
            ))}
          </Document>)) : (filetype === 'xlsx' ? ((<Table columns={columns2} dataSource={data2} rowKey={'商品ID'} pagination={false} />)) : (<img style={{ width: 500 }} src={file} />))) : '')
        }
      </Modal>
      {
        searchIf ? (<Table
          columns={columns}
          pagination={false}
          rowSelection={{
            ...rowSelection,
            checkStrictly,
          }}
          dataSource={data}
        />) : (<Table
          columns={columns}
          pagination={false}
          rowSelection={{
            ...rowSelection,
            checkStrictly,
          }}
          dataSource={data3}
        />)
      }
    </div>
  );
};

export default Index;
